package com.xiaoxu.privatechat.controller.home;

import com.xiaoxu.privatechat.bean.CodeMsg;
import com.xiaoxu.privatechat.bean.Result;
import com.xiaoxu.privatechat.constant.SessionConstant;
import com.xiaoxu.privatechat.entity.common.Account;
import com.xiaoxu.privatechat.service.admin.OperaterLogService;
import com.xiaoxu.privatechat.service.common.AccountService;
import com.xiaoxu.privatechat.util.SessionUtil;
import com.xiaoxu.privatechat.util.StringUtil;
import com.xiaoxu.privatechat.util.ValidateEntityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @author xiaoxu
 * @description 前台首页控制器
 * @date 2023/2/13
 */
@RequestMapping("/home/index")
@Controller
public class HomeIndexController {

    @Resource
    private AccountService accountService;

    @Resource
    private OperaterLogService operaterLogService;

    private final Logger log = LoggerFactory.getLogger(HomeIndexController.class);

    /**
     * @return String
     * @description 登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "home/index/login";
    }

    /**
     * @return String
     * @description 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        Account onlineAccount = (Account) SessionUtil.get(SessionConstant.SESSION_ACCOUNT_LOGIN_KEY);
        onlineAccount = accountService.find(Objects.requireNonNull(onlineAccount).getId());
        onlineAccount.setChatStatus(Account.ACOUNT_CHAT_STATUS_OFFLINE);
        accountService.save(onlineAccount);
        SessionUtil.set(SessionConstant.SESSION_ACCOUNT_LOGIN_KEY, null);
        return "redirect:login";
    }

    /**
     * @return String
     * @description 注册页面
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
        return "home/index/register";
    }

    /**
     * @param account 用户信息
     * @return Result
     * @description 提交注册表单
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> register(Account account) {
        if (account == null) {
            return Result.error(CodeMsg.DATA_ERROR);
        }
        //用统一验证实体方法验证是否合法
        CodeMsg validate = ValidateEntityUtil.validate(account);
        if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
            return Result.error(validate);
        }
        //检查用户名是否重复
        if (accountService.isExistUsername(account.getUsername(), 0L)) {
            return Result.error(CodeMsg.ACCOUNT_USERNAME_EXIST);
        }
        if (accountService.register(account) == null) {
            return Result.error(CodeMsg.ACCOUNT_REGISTER_ERROR);
        }
        operaterLogService.add("用戶【" + account.getUsername() + "】于【" + StringUtil.getFormatterDate(new Date(), "yyyy-MM-dd HH:mm:ss") + "】注冊成功！");
        log.info("用戶注冊成功，user = " + account);
        return Result.success(true);
    }

    /**
     * @param account 用户信息
     * @return Result
     * @description 登录表单提交
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> login(Account account) {
        if (account == null) {
            return Result.error(CodeMsg.DATA_ERROR);
        }
        Account findByUsername = accountService.findByUsername(account.getUsername());
        if (findByUsername == null) {
            return Result.error(CodeMsg.ACCOUNT_USERNAME_NO_EXIST);
        }
        //检查密码是否正确
        if (!findByUsername.getPassword().equals(account.getPassword())) {
            return Result.error(CodeMsg.ACCOUNT_PASSWORD_ERROR);
        }
        //检查状态是否正常
        switch (findByUsername.getStatus()) {
            case Account.ACOUNT_USER_STATUS_UNABLE:
                return Result.error(CodeMsg.ACCOUNT_STATUS_UNABLE);
            case Account.ACOUNT_USER_STATUS_EXAMINE:
                return Result.error(CodeMsg.ACCOUNT_STATUS_EXAMINE);
            case Account.ACOUNT_USER_STATUS_ENABLE:
                break;
            default:
                return Result.error(CodeMsg.ACCOUNT_STATUS_ERROR);
        }
        //登录成功，修改在线状态为上线
        findByUsername.setChatStatus(Account.ACOUNT_CHAT_STATUS_ONLINE);
        accountService.save(findByUsername);
        //将用户信息写入session
        SessionUtil.set(SessionConstant.SESSION_ACCOUNT_LOGIN_KEY, findByUsername);
        operaterLogService.add("用戶【" + account.getUsername() + "】于【" + StringUtil.getFormatterDate(new Date(), "yyyy-MM-dd HH:mm:ss") + "】登錄成功！");
        log.info("用戶成功登錄，user = " + account);
        return Result.success(true);
    }
}
